#include <linux/skbuff.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/vmalloc.h>
#include <rdma/uverbs_ioctl.h>

#include "rxe.h"
#include "rxe_loc.h"
#include "rxe_queue.h"
#include "rxe_task.h"

static int rxe_qp_chk_cap(struct rxe_dev *rxe, struct ib_qp_cap *cap,
              int has_srq)
{
    if (cap->max_send_wr > rxe->attr.max_qp_wr) {
        pr_warn("invalid send wr = %d > %d\n",
            cap->max_send_wr, rxe->attr.max_qp_wr);
        goto err1;
    }

    if (cap->max_send_sge > rxe->attr.max_send_sge) {
        pr_warn("invalid send sge = %d > %d\n",
            cap->max_send_sge, rxe->attr.max_send_sge);
        goto err1;
    }

    if (!has_srq) {
        if (cap->max_recv_wr > rxe->attr.max_qp_wr) {
            pr_warn("invalid recv wr = %d > %d\n",
                cap->max_recv_wr, rxe->attr.max_qp_wr);
            goto err1;
        }

        if (cap->max_recv_sge > rxe->attr.max_recv_sge) {
            pr_warn("invalid recv sge = %d > %d\n",
                cap->max_recv_sge, rxe->attr.max_recv_sge);
            goto err1;
        }
    }

    if (cap->max_inline_data > rxe->max_inline_data) {
        pr_warn("invalid max inline data = %d > %d\n",
            cap->max_inline_data, rxe->max_inline_data);
        goto err1;
    }

    return 0;

err1:
    return -EINVAL;
}

int rxe_qp_chk_init(struct rxe_dev *rxe, struct ib_qp_init_attr *init)
{
    struct ib_qp_cap *cap = &init->cap;
    struct rxe_port *port;
    int port_num = init->port_num;

    //专门用于收发MAD层管理报文，QP0,QP1
    switch (init->qp_type) {
    //https://zhuanlan.zhihu.com/p/494826608?utm_id=0
        case IB_QPT_SMI:
        case IB_QPT_GSI:
        case IB_QPT_RC:
        case IB_QPT_UC:
        case IB_QPT_UD:
            break;
        default:
            return -EOPNOTSUPP;
    }

    if (!init->recv_cq || !init->send_cq) {
        pr_warn("missing cq\n");
        goto err;
    }

    if (rxe_qp_chk_cap(rxe, cap, !!init->srq))
        goto err1;

    if (init->qp_type == IB_QPT_SMI || init->qp_type == IB_QPT_GSI) {
        if (!rdma_is_port_valid(&rxe->ib_dev, port_num)) {
            pr_warn("invalid port = %d\n", port_num);
            goto err1;
        }

        port = &rxe->port;

        if (init->qp_type == IB_QPT_SMI && port->qp_smi_index) {
            pr_warn("SMI QP exists for port %d\n", port_num);
            goto err1;
        }

        if (init->qp_type == IB_QPT_GSI && port->qp_gsi_index) {
            pr_warn("GSI QP exists for port %d\n", port_num);
            goto err1;
        }
    }

    return 0;
err:
    return -EINVAL;
}

static int alloc_rd_atomic_resources(struct rxe_qp *qp, unsigned int n)
{
    qp->resp.res_head = 0;
    qp->resp.res_tail = 0;

    qp->resp.resource = kcalloc(n, sizeof(struct resp_res), GFP_KERNEL);
    if(!qp->resp.resource)
        return -ENOMEM;

    return 0;
}

static void free_rd_atomic_resources(struct rxe_qp *qp)
{
    if(qp->resp.resources) {
        int i;

        for(i = 0; i < qp->attr.max_dest_rd_atomic; i++) {
            struct resp_res *res = &qp->resp.resources[i];

            free_rd_atomic_resource(qp, res);
        }
        kfree(qp->resp.resource);
        qp->resp.resource = NULL;
    }
    return 0;
}

void free_rd_atomic_resource(struct rxe_qp *qp, struct resp_res *res)
{


}

static void cleanup_rd_atomic_resources(struct rxe_qp *qp)
{
    int i;
    struct resp_res *res;
    if(qp->resp.resources) {
        for(i = 0; i < qp->attr.max_dest_rd_atomic; i++) {
            res = &qp->resp.resources[i];
            free_rd_atomic_resource(qp, res);
        }
    }
}

static void rxe_qp_init_misc(struct rxe_dev *rxe, struct rxe_qp *qp,
        struct ib_qp_init_attr *init)
{
    struct rxe_port *port;
    u32 qpn;

    qp->sq_sig_type = init->sq_sig_type;
    qp->attr.path_mtu = 1;
    qp->mtu = ib_mtu_enum_to_int(qp->attr.path_mtu);

    qpn = qp->pelem.index;
    port = &rxe->port;

    switch (init->qp_type) {
    case IB_QPT_SMI:
        qp->ibqp.qp_num = 0;
        port->qp_smi_index = qpn;
        qp->attr.port_num = init->port_num;
        break;

    case IB_QPT_GSI:
        qp->ibqp.qp_num = 1;
        port->qp_gsi_index = qpn;
        qp->attr.port_num = init->port_num;
        break;

    default:
        qp->ibqp.qp_num = qpn;
        break;
    }

    INIT_LIST_HEAD(&qp->grp_list);

    skb_queue_head_init(&qp->send_pkts);

    spin_lock_init(&qp->grp_lock);
    spin_lock_init(&qp->state_lock);

    spin_lock_init(&qp->req.task.state_lock);
    spin_lock_init(&qp->resp.task.state_lock);
    spin_lock_init(&qp->comp.task.state_lock);

    spin_lock_init(&qp->sq.sq_lock);
    spin_lock_init(&qp->rq.producer_lock);
    spin_lock_init(&qp->rq.consumer_lock);

    atomic_set(&qp->ssn, 0);
    atomic_set(&qp->skb_out, 0);
}

static int rxe_qp_init_req(struct rxe_dev *rxe, struct rxe_qp *qp,
        struct ib_qp_init_attr *init, struct ib_udata *udata,
        struct rxe_create_qp_resp __user *uresp)
{
    int err;
    int wqe_size;
    enum queue_type type;

    err = sock_create_kern(&init_net, AF_INET, SOCK_DGRAM, 0, &qp->sk);
    if (err < 0)
        return err;
    qp->sk->sk->sk_user_data = qp;

    /*qp源端口号*/
    qp->src_port = RXE_ROCE_V2_SPORT + (hash_32_generic(qp_num(qp), 14) & 0x3fff);
    qp->sq.max_wr = init->cap.max_send_wr;
    wqe_size = max_t(int, init->cap.max_send_sge * sizeof(struct ib_sge), init->cap.max_inline_data);
    qp->sq.max_sge = init->cap.max_send_sge = wqe_size / sizeof(struct ib_sge);
    qp->sq.max_inline = init->cap.max_inline_data = wqe_size;

    /*得到最终的每一个wqe的大小*/
    wqe_size += sizeof(struct rxe_send_wqe);

    type = QUEUE_TYPE_FROM_CLIENT;

    /*发送队列缓冲区申请*/
    qp->sq.queue = rxe_queue_init(rxe, &qp->sq.max_wr, wqe_size, type);
    if(!qp->sq.queue)
        return -ENOMEM;

    /*将队列映射到用户空间*/
    err = do_mmap_info(rxe, uresp ? &uresp->sq_mi : NULL, udata,
            qp->sq.queue->buf, qp->sq.queue->buf_size, &qp->sq.queue->ip);
    if(err) {
        vfree(qp->sq.queue->buf);
        kfree(qp->sq.queue);
        qp->sq.queue = NULL;
        return err;
    }

    /*现在应该是第一个位置*/
    qp->req.wqe_index = queue_get_producer(qp->sq.queue, QUEUE_TYPE_FROM_CLIENT);

    qp->req.state = QP_STATE_RESET;
    qp->req.opcode = -1;
    qp->comp.opcode = -1;

    /*请求包使用skb队列管理*/
    skb_queue_head_init(&qp->req_pkts);

    rxe_init_task(rxe, &qp->req.task, qp, rxe_requester, "req");
    rxe_init_task(rxe, &qp->comp.task, qp, rxe_completer, "comp");

    /* Can't be set for UD/UC in modify_qp */
    qp->qp_timeout_jiffies = 0;
    if (init->qp_type == IB_QPT_RC) {
        /*定时器初始化*/
        timer_setup(&qp->rnr_nak_timer, rnr_nak_timer, 0);
        timer_setup(&qp->retrans_timer, retransmit_timer, 0);
    }

    return 0；
}

static int rxe_qp_init_resp(struct rxe_dev *rxe, struct rxe_qp *qp,
        struct ib_qp_init_attr *init,
        struct ib_udata *udata,
        struct rxe_create_qp_resp __user *uresp)
{
    int err;
    int wqe_size;
    enum queue_type type;

    if(!qp->srq) {
        qp->rq.max_wr = init->cap.max_recv_wr;
        qp->rq.max_sge = init->cap.max_recv_sge;

        wqe_size = rcv_wqe_size(qp->rq.max_sge);
        pr_debug("qp#%d max_wr = %d, max_sge = %d, wqe_size = %d\n",
            qp_num(qp), qp->rq.max_wr, qp->rq.max_sge, wqe_size);

        type = QUEUE_TYPE_FROM_CLIENT;

        /*接收队列缓冲区申请*/
        qp->rq.queue = rxe_queue_init(rxe, &qp->rq.max_wr, wqe_size, type);
        if (!qp->rq.queue)
            return -ENOMEM;

        /*接收队列缓冲区映射*/
        err = do_mmap_info(rxe, uresp ? &uresp->rq_mi : NULL, udata,
               qp->rq.queue->buf, qp->rq.queue->buf_size, &qp->rq.queue->ip);
        if (err) {
            vfree(qp->rq.queue->buf);
            kfree(qp->rq.queue);
            qp->rq.queue = NULL;
            return err;
        }
    }
    /*skb队列初始化*/
    skb_queue_head_init(&qp->resp_pkts);
    rxe_init_task(rxe, &qp->resp.task, qp, rxe_responder, "resp");

    qp->resp.opcode = OPCODE_NONE;
    /*消息序列号-ack包填充需要该字段*/
    qp->resp.msn = 0;
    qp->resp.state = QP_STATE_RESET;

    return 0;
}

int rxe_qp_from_init(struct rxe_dev *rxe, struct rxe_qp *qp, struct rxe_pd *pd,
        struct ib_qp_init_attr *init,
        struct rxe_create_qp_resp __user *uresp,
        struct ib_pd *ibpd,
        struct ib_udata *udata)
{
    int err;
    struct rxe_cq *rcq = to_rcq(init->recv_cq);
    struct rxe_cq *scq = to_rcq(init->send_cq);
    struct rxe_srq *srq = init->srq ? to_rsrq(init->srq) : NULL;

    rxe_add_ref(pd);
    rxe_add_ref(rcq);
    rxe_add_ref(scq);
    if (srq)
        rxe_add_ref(srq);

    qp->pd = pd;
    qp->rcq = rcq;
    qp->scq = scq;
    qp->srq = srq;

    //struct rxe_qp *qp里面一些成员的初始化
    rxe_qp_init_misc(rxe, qp, init);

    err = rxe_qp_init_req(rxe, qp, init, udata, uresp);
    if (err)
        goto err1;

    err = rxe_qp_init_resp(rxe, qp, init, udata, uresp);
    if (err)
        goto err2;

    //创建qp后qp的初始状态
    qp->attr.qp_state = IB_QPS_RESET;
    qp->valid = 1;

    return 0;
err2:
    rxe_queue_cleanup(qp->sq.queue);
    qp->sq.queue = NULL;
err1:
    qp->pd = NULL;
    qp->rcq = NULL;
    qp->scq = NULL;
    qp->srq = NULL;

    if (srq)
        rxe_drop_ref(srq);
    rxe_drop_ref(scq);
    rxe_drop_ref(rcq);
    rxe_drop_ref(pd);
    return err;
}

int rxe_qp_to_init(struct rxe_qp *qp, struct ib_qp_init_attr *init)
{
    init->event_handler = qp->ibqp.event_handler;
    init->qp_context = qp->ibqp.qp_context;
    init->send_cq = qp->ibqp.send_cq;
    init->recv_cq = qp->ibqp.recv_cq;
    init->srq = qp->ibqp.srq;

    init->cap.max_send_wr = qp->sq.max_wr;
    init->cap.max_send_sge = qp->sq.max_sge;
    init->cap.max_inline_data = qp->sq.max_inline;

    if (!qp->srq) {
        init->cap.max_recv_wr = qp->rq.max_wr;
        init->cap.max_recv_sge = qp->rq.max_sge;
    }

    init->sq_sig_type = qp->sq_sig_type;
    init->qp_type = qp->ibqp.qp_type;
    init->port_num = 1;

    return 0;
}

int rxe_qp_chk_attr(struct rxe_dev *rxe, struct rxe_qp *qp,
        struct ib_qp_attr *attr, int mask)
{


    return 0;

err1:
    return -EINVAL;
}

static void rxe_qp_reset(struct rxe_qp *qp)
{




}

/* drain the send queue */
static void rxe_qp_drain(struct rxe_qp *qp)
{
    if(qp->sq.queue) {
        if() {



        }

    }
}

/* move the qp to the error state */
void rxe_qp_error(struct rxe_qp *qp)
{
    qp->req.state = QP_STATE_ERROR;
    qp->resp.state = QP_STATE_ERROR;
    qp->attr.qp_state = IB_QPS_ERR;



}

int rxe_qp_from_attr(struct rxe_qp *qp, struct ib_qp_attr *attr, int mask,
        struct ib_udata *udata)
{
    int err;

    if (mask & IB_QP_MAX_QP_RD_ATOMIC) {
        int max_rd_atomic = attr->max_rd_atomic ?
            roundup_pow_of_two(attr->max_rd_atomic) : 0;

        qp->attr.max_rd_atomic = max_rd_atomic;
        atomic_set(&qp->req.rd_atomic, max_rd_atomic);
    }


    if (mask & IB_QP_MAX_DEST_RD_ATOMIC) {

    }

    if (mask & IB_QP_PATH_MIG_STATE)
        qp->attr.path_mig_state = attr->path_mig_state;

    if (mask & IB_QP_DEST_QPN)
        qp->attr.dest_qp_num = attr->dest_qp_num;

    if (mask & IB_QP_CUR_STATE)
        qp->attr.cur_qp_state = attr->qp_state;

    if (mask & IB_QP_EN_SQD_ASYNC_NOTIFY)
        qp->attr.en_sqd_async_notify = attr->en_sqd_async_notify;

    if (mask & IB_QP_ACCESS_FLAGS)
        qp->attr.qp_access_flags = attr->qp_access_flags;

    if (mask & IB_QP_PKEY_INDEX)
        qp->attr.pkey_index = attr->pkey_index;

    if (mask & IB_QP_PORT)
        qp->attr.port_num = attr->port_num;

    if (mask & IB_QP_QKEY)
        qp->attr.qkey = attr->qkey;

    if(mask & IB_QP_AV)
        rxe_init_av(&attr->ah_attr, &qp->priav);

    if (mask & IB_QP_ALT_PATH) {

    }

    /*回复ack/nack的最小时间*/
    if(mask & IB_QP_TIMEOUT) {
        qp->attr.timeout = attr->timeout;
        if (attr->timeout == 0) {
            qp->qp_timeout_jiffies = 0;
        } else {
            /* According to the spec, timeout = 4.096 * 2 ^ attr->timeout [us]
                纳秒转jiffies值*/
            int j = nsecs_to_jiffies(4096ULL << attr->timeout);
            qp->qp_timeout_jiffies = j ? j : 1;
        }
    }

    if (mask & IB_QP_PATH_MTU) {
        qp->attr.path_mtu = attr->path_mtu;
        qp->mtu = ib_mtu_enum_to_int(attr->path_mtu);
    }

    if (mask & IB_QP_RETRY_CNT) {
        qp->attr.retry_cnt = attr->retry_cnt;
        qp->comp.retry_cnt = attr->retry_cnt;
        pr_debug("qp#%d set retry count = %d\n", qp_num(qp),
            attr->retry_cnt);
    }

    if (mask & IB_QP_RNR_RETRY) {
        qp->attr.rnr_retry = attr->rnr_retry;
        qp->comp.rnr_retry = attr->rnr_retry;
        pr_debug("qp#%d set rnr retry count = %d\n", qp_num(qp),
         attr->rnr_retry);
    }

    /*qp状态的修改,所以应用层要修改状态，必须要与上该位*/
    if(mask & IB_QP_STATE) {
        /*从应用层得到要修改的qp状态*/
        qp->attr.qp_state = attr->qp_state;

        /*qp的状态转换*/
        switch(attr->qp_state) {
        case IB_QPS_RESET://RESET
            pr_debug("qp#%d state -> RESET\n", qp_num(qp));
            rxe_qp_reset(qp);
            break;

        case IB_QPS_INIT://Initialized
            pr_debug("qp#%d state -> INIT\n", qp_num(qp));
            qp->req.state = QP_STATE_INIT;
            qp->resp.state = QP_STATE_INIT;
            break;

        case IB_QPS_RTR://Ready to Receive
            pr_debug("qp#%d state -> RTR\n", qp_num(qp));
            qp->resp.state = QP_STATE_READY;
            break;

        case IB_QPS_RTS://Ready to Send
            pr_debug("qp#%d state -> RTS\n", qp_num(qp));
            qp->req.state = QP_STATE_READY;
            break;

        case IB_QPS_SQD://SQ Drain
            pr_debug("qp#%d state -> SQD\n", qp_num(qp));
            rxe_qp_drain(qp);
            break;

        case IB_QPS_SQE://SQ Error
            pr_warn("qp#%d state -> SQE !!?\n", qp_num(qp));
            break;

        case IB_QPS_ERR://ERROR
            pr_debug("qp#%d state -> ERR\n", qp_num(qp));
            rxe_qp_error(qp);
            break;
        }
    }

    return 0;
}

/* called by the query qp verb */
int rxe_qp_to_attr(struct rxe_qp *qp, struct ib_qp_attr *attr, int mask)
{
    *attr = qp->attr;

    attr->rq_psn = qp->resp.psn;
    attr->sq_psn = qp->req.psn;

    attr->cap.max_send_wr = qp->sq.max_wr;
    attr->cap.max_send_sge = qp->sq.max_sge;
    attr->cap.max_inline_data = qp->sq.max_inline;

    if (!qp->srq) {
        attr->cap.max_recv_wr = qp->rq.max_wr;
        attr->cap.max_recv_sge = qp->rq.max_sge;
    }

    rxe_av_to_attr(&qp->pri_av, &attr->ah_attr);
    rxe_av_to_attr(&qp->alt_av, &attr->alt_ah_attr);

    if (qp->req.state == QP_STATE_DRAIN) {
        attr->sq_draining = 1;
        /* applications that get this state
         * typically spin on it. yield the
         * processor
         */
        cond_resched();
    } else {
        attr->sq_draining = 0;
    }

    pr_debug("attr->sq_draining = %d\n", attr->sq_draining);

    return 0;
}

void rxe_qp_destroy(struct rxe_qp *qp)
{
    qp->valid = 0;
    qp->qp_timeout_jiffies = 0;


}

static void rxe_qp_do_cleanup(struct work_struct *work)
{
    struct rxe_qp *qp = container_of(work, typeof(*qp), cleanup_work.work);


    kernel_sock_shutdown(qp->sk, SHUT_RDWR);
    sock_release(qp->sk);
}

void rxe_qp_cleanup(struct rxe_pool_entry *arg)
{
    struct rxe_qp *qp = container_of(arg, typeof(*qp), pelem);


}

